package com.xm.settlement.service.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xm.settlement.commons.base.ApiSQLException;
import com.xm.settlement.commons.shiro.ShiroUser;
import com.xm.settlement.commons.utils.*;
import com.xm.settlement.mapper.*;
import com.xm.settlement.model.*;
import com.xm.settlement.model.form.UserTree;
import com.xm.settlement.model.vo.AppUserVo;
import com.xm.settlement.model.vo.UserVo;
import com.xm.settlement.service.AppShopLogService;
import com.xm.settlement.service.AppUserService;
import com.xm.settlement.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Administrator on 2017/2/7.
 */
@Service
public class AppUserServiceImpl extends SuperServiceImpl<AppUserMapper,AppUser> implements AppUserService {

    @Autowired  private  AppUserMapper appUserMapper;
    @Autowired  private AppUserManageMapper appUserManageMapper;
    @Autowired  private UserMapper userMapper;
    @Autowired  private UserRoleMapper userRoleMapper;
    @Autowired  private OrganizationMapper organizationMapper;
    @Autowired  private IUserService userService;
    @Autowired  private RedisTemplate redisTemplate;
    @Autowired  private RedisCacheUtil redisCacheUtil;
    @Autowired  private AppShopLogService appShopLogService;
    @Autowired  private AppUserService appUserService;

    private String uuId;

    @Override
    public void selectDataGrid(PageInfo pageInfo, Long lid) {
        Page<User> page = new Page<User>(pageInfo.getNowpage(), pageInfo.getSize());
        if(lid != null){
            User user = userMapper.selectById(lid);
            pageInfo.getCondition().put("login_name",user.getLoginName());
        }
        List<User> list = appUserMapper.selectUserVoList(page,pageInfo.getCondition());
        pageInfo.setRows(list);
        pageInfo.setTotal(page.getTotal());
    }

    /**
     * 保存用户在这边实现
     * ，收益调用服务器接口
     * */
    @Override
    public void insertAppUser(AppUserVo appUserVo, Long lid) throws InterruptedException, UnsupportedEncodingException, URISyntaxException, ApiSQLException {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try {
            /**
             * 1.插入app_user表数据
             * 2.插入app_user_manage
             * 3.调用系统送积分接口
             * */
            AppUser appUser = BeanUtils.copy(appUserVo,AppUser.class);
            //isUsedAccount(appUser);
            appUser.setPhone(appUserVo.getPhone().toString());
            if (appUser.getService_code() == null){
                User user = userMapper.selectById(lid);
                appUser.setService_code(  user.getLoginName() );
            }
            appUser.setCreateTime(new Date());
            appUser.setPassword(appUserVo.getPassword());
            appUser.setTwo_password(DigestUtils.md5Hex(StringUtils.isNotBlank(appUser.getPassword())?appUser.getPassword():appUser.getPhone().substring(5,11)));
            appUser.setStatus(1);
            appUserMapper.insert(appUser);

            AppUserManage appUserManage =  BeanUtils.copy(appUserVo,AppUserManage.class);
            appUserManage.setDirect_num(0);
            appUserManage.setIndirect_num(0.0);
            appUserManage.setCash_score(0.0);
            appUserManage.setShop_score(0.0);
            appUserManage.setElect_score(0.0);
            appUserManage.setOption_score(0.0);
            appUserManage.setVip_level(1);
            appUserManage.setCreate_id(lid);
            appUserManage.setCreate_time(new Date());
            appUserManage.setPresent_score(0.0);
            appUserManageMapper.insert(appUserManage);
            //-----------------------------------------
            //   调用支付充值接口
            //-----------------------------------------
            if(appUserVo.getAwards() >= 3000  ){
                appShopLogService.changeDynamicIncome(appUserManage.getVip_code(),appUserVo.getAwards());
            }

        }finally {
            lock.unlock();
        }
    }

    /**
     * 保存用户在这边实现
     * ，收益调用服务器接口
     *
     * */
    @Override
    public void insertAppuserByExcel(String filePath,String fileName) throws ApiSQLException {
        List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);	//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet


    }

    public boolean isUsedAccount(AppUser user) throws ApiSQLException{
        AppUser userParams = new AppUser();
        //--------------------------------------------------
        //  判断缓存中是否存在
        //--------------------------------------------------
        AppUserVo appUserVo = (AppUserVo) redisCacheUtil.getCacheObject(RedisBeanUtils.USER_VO_MAP +"_"+user.getVip_code());
        if( appUserVo != null ){
            throw new ApiSQLException(101,"会员已注册");
        }else{
            userParams.setVip_code(user.getVip_code());
            List<AppUser> list = selectByParams(userParams);
            if (list != null && !list.isEmpty()) {
                throw new ApiSQLException(101,"会员已注册");
            }
            userParams.setVip_code(null);
        }
        if(redisCacheUtil.getCacheObject(RedisBeanUtils.USER_VO_MAP +"_"+user.getPush_code()) == null ){
            throw new ApiSQLException(118,"推荐人编号系统不存在");
        }else{
            userParams.setVip_code(user.getPush_code());
            List<AppUser> list = selectByParams(userParams);
            if (list == null || list.isEmpty()) {
                throw new ApiSQLException(118,"推荐人编号系统不存在");
            }
            userParams.setPush_code(null);
        }
        return  true;
    }


    public List<AppUser> selectByParams(AppUser user) {
        EntityWrapper<AppUser> wrapper = new EntityWrapper<AppUser>(user);
        if (null != user.getId()) {
            wrapper.and("id != {0}", user.getId());
        }
        if (null != user.getVip_code()) {
            wrapper.and("vip_code = {0}", user.getVip_code());
        }
        return this.selectList(wrapper);
    }


    private ConcurrentHashMap<Long,Integer> concurrentHashMap = new ConcurrentHashMap<Long,Integer>();

    @Override
    public List<AppUserVo> selectUserVoList() {
        return appUserMapper.selectUserVoList();
    }

    @Override
    public List<AppUserVo> getChildrenNodeByParentVipCode(String vip_code) {
        return appUserMapper.getChildrenNodeByParentVipCodeList(vip_code);
    }

    @Override
    public List<AppUserVo> selectUserVoListByParam(AppUserVo appUserVo) {
        return appUserMapper.selectUserVoListByParam(appUserVo);
    }


    @Override
    public List selectDataGridTree(String vipCode,Long userId){
        /**-------------------------
         *   第一层数据
         * -------------------------*/
        if(StringUtils.isNotBlank(vipCode)){
            List  lastList  = new CopyOnWriteArrayList();
            AppUserManage appUserManage = new AppUserManage();
            appUserManage.setVip_code(vipCode);
            appUserManage = appUserManageMapper.selectOne(appUserManage);
            if(appUserManage == null ){
                return  lastList;
            }
            UserTree userTree = new UserTree();
            userTree.setName("人数："+appUserManage.getDirect_num()+"  业绩"+ appUserManage.getIndirect_num()/10000 +"万");
            userTree.setVip_code(vipCode);
            userTree.setPhone(vipCode);
            userTree.setValue(vipCode);
            EntityWrapper wrapper = new EntityWrapper();
            wrapper.where("  vip_code in (  select vip_code from app_user where  push_code = {0} ) ",vipCode);
            List<AppUserManage> firstChildrenList = appUserManageMapper.selectList(wrapper);
            if(firstChildrenList != null && firstChildrenList.size()>0){
                CopyOnWriteArrayList<UserTree> cpList = new CopyOnWriteArrayList<UserTree> ();

                for (AppUserManage appUserVo : firstChildrenList ){
                    UserTree  userTree1 = new UserTree();
                    userTree1.setVip_code(appUserVo.getVip_code());
                    userTree1.setPhone(appUserVo.getVip_code());
                    userTree1.setValue(vipCode);
                    userTree1.setName("人数："+ appUserVo.getDirect_num()+"  业绩"+ appUserVo.getIndirect_num()/10000 +"万");
                    if(appUserVo.getVip_code() !=null && !StringUtils.isEmpty(appUserVo.getVip_code())  && !appUserVo.getVip_code().equals("null")){
                        userTree1.setChildren(grideNode(appUserVo.getVip_code()));
                    }
                    cpList.add( userTree1 );
                }
                userTree.setChildren(cpList);
            }
            lastList.add(userTree);
            return lastList;
        }else{
            treeList =  new CopyOnWriteArrayList();
            User user = userMapper.selectById(userId);
            /**---------------------------------------
             *  当前平台下的全部平台数据
             * ------------------------------------*/
            treeList.add(user.getOrganizationId());

            getChildrenTree(user.getOrganizationId());
            List<UserTree>  lastList     =  appUserManageMapper.selectUserTree( treeList  );
            UserTree userTree ;
            for (UserTree tree : lastList ){
                tree.setChildren(grideNode(tree.getVip_code()));
            }
            return lastList;
        }

    }


    private List treeList =  new CopyOnWriteArrayList();

    public void  getChildrenTree(Integer organizationId){
        if(organizationId == null || organizationId < 0 ){
            return ;
        }
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.where(" pid = {0} " ,organizationId);
        List<Organization> list =  organizationMapper.selectList(entityWrapper);
        for (Organization o : list ){
            treeList.add(o.getId());
            getChildrenTree(o.getId().intValue());
        }
    }


    /**
     * 递归查询全部子节点
     * */
    public List grideNode(String vipCode){
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.where("  vip_code in (  select vip_code from app_user where  push_code = {0} ) ",vipCode);
        List<AppUserManage> childrenList = appUserManageMapper.selectList(wrapper);
        CopyOnWriteArrayList<UserTree> cpList = new CopyOnWriteArrayList<UserTree> ();

        if(childrenList != null && childrenList.size()>0){
            for (AppUserManage appUserVo : childrenList ){
                UserTree  userTree1 = new UserTree();
                userTree1.setName("人数："+ appUserVo.getDirect_num()+"  业绩"+ appUserVo.getIndirect_num()/10000 +"万");
                userTree1.setVip_code(appUserVo.getVip_code());
                userTree1.setPhone(appUserVo.getVip_code());
                userTree1.setValue(vipCode);

                if(appUserVo.getVip_code() !=null && !StringUtils.isEmpty(appUserVo.getVip_code()) && !appUserVo.getVip_code().equals("null")){
                    userTree1.setChildren(grideNode(appUserVo.getVip_code()));
                }
                cpList.add( userTree1 );
            }
        }
        return cpList;
    }



    @Override
    public void insertAccount(AppUserVo appUserVo1,  ShiroUser shiroUser) throws InterruptedException, URISyntaxException, ApiSQLException, UnsupportedEncodingException {
        User user1 = new User();
        User user2 = new User();
        user2.setLoginName(appUserVo1.getVip_code());
        user2 =  userMapper.selectOne(user2);
        if(user2 != null ){
                throw new ApiSQLException(101,"会员已注册");
        }

        user1.setLoginName(appUserVo1.getPush_code());
         user1 =  userMapper.selectOne(user1);
        appUserVo1.setOrganizationId(user1.getOrganizationId().longValue());
        UserVo userVo = new UserVo();
        userVo.setLoginName(appUserVo1.getVip_code());
        userVo.setPhone(appUserVo1.getVip_code());
        userVo.setCreateTime(new Date());
        userVo.setName(appUserVo1.getVip_code());
        userVo.setOrganizationId(user1.getOrganizationId());
        userVo.setRoleIds("2");
        userVo.setUserType(2);
        userVo.setStatus(0);


        SendSMS sendSMS = new SendSMS();
        String password = UUID.randomUUID().toString().substring(0,8);
        User user = BeanUtils.copy(userVo, User.class);
        user.setCreateTime(new Date());
        user.setPassword(DigestUtils.md5Hex(appUserVo1.getPassword() == null ? password:appUserVo1.getPassword()  ));
        userService.insert(user);


        String passwordMd5 =  DigestUtils.md5Hex(password);

        Long id = user.getId();

        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        userRole.setRoleId(2l);
        userRoleMapper.insert(userRole);

        //--- 添加到表 app_user app_manage
        AppUserVo appUserVo = new AppUserVo();
        appUserVo.setVip_code(userVo.getPhone());
        appUserVo.setName(userVo.getName());
        appUserVo.setPassword(passwordMd5);
        appUserVo.setPhone(Long.valueOf(appUserVo1.getPhone()));
        appUserVo.setStatus(1);
        appUserVo.setCreate_time(new Date());
        //
        UserVo userVo1 = userService.selectVoById(shiroUser.getId());
        appUserVo.setPush_code(appUserVo1.getPush_code());
        appUserVo.setService_code(userVo1.getPhone());
        appUserVo.setAwards(appUserVo1.getAwards());
        try{
            insertAppUser(appUserVo,shiroUser.getId());
            sendSMS.sendAccount(userVo1.getPhone(),password);
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }


    CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<String>();
  @Override
    public void updateappEditOrigin(String vipCode, String originId) {

        EntityWrapper wrapper = new EntityWrapper();
        wrapper.where("  login_name in (  select vip_code from app_user where  push_code = {0} ) ",vipCode);
        List<User> firstChildrenList =  userMapper.selectList(wrapper);
        if(firstChildrenList != null && firstChildrenList.size()>0){

                for(User appUserManage : firstChildrenList){
                    copyOnWriteArrayList.add(appUserManage.getLoginName());
                    getChildrenList(appUserManage.getLoginName());
                }
        }
        //循环修改
        if(copyOnWriteArrayList == null || copyOnWriteArrayList.size()<=0 ){
            return;
        }
        Map map = new HashMap();
        map.put("organizationId",originId);
        map.put("stringList",copyOnWriteArrayList);
        userMapper.updateBatchMap(map);

    }

    /**
     * 递归查询 并修改
     * */
    public void getChildrenList(String vipCode){
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.where("  login_name in (  select vip_code from app_user where  push_code = {0} ) ",vipCode);
        List<User> childrenList = userMapper.selectList(wrapper);
        if(childrenList != null && childrenList.size()>0){
            for (User appUserVo : childrenList ){
                copyOnWriteArrayList.add(appUserVo.getLoginName());
                getChildrenList(appUserVo.getLoginName());
            }
        }
    }


}

